package com.link.base.wechat.mpnews.service;

import com.link.base.wechat.mpnews.model.Article;
import com.link.base.wechat.mpnews.util.ArticleUtil;
import com.link.base.wechat.wxlog.model.WxLogModule;
import com.link.base.wechat.wxlog.service.WxLogService;
import com.link.base.wechat.wxtoken.model.WxToken;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.JsonUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号素材管理实现类
 *
 * @author lujiang
 * @date 2019/02/26 16:30
 */
@Service
public class ArticleServiceImpl extends BasicServiceImpl<Article> implements ArticleService {

    @Resource
    private WxTokenService wxTokenService;

    @Resource
    private WxLogService wxLogService;

    @Override
    public Map<String, Object> uploadArticles(String wxAppid, List<Article> articleList) throws Exception {
        WxToken wxToken = wxTokenService.getWxAccessTokenByAppId(wxAppid);
        String accessToken = wxToken.getAccess_token();
        // 数据检验
        checkArticle(accessToken, articleList);
        // 获取参数json字符串
        Map<String, Object> map = new HashMap<>(16);
        Map<String, Object> articlesmap = new HashMap<>(16);
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < articleList.size(); i++) {
            Article article = articleList.get(i);
            Map<String, Object> resultmap = new HashMap<>(16);
            resultmap.put("thumb_media_id", article.getThumbMediaId());
            resultmap.put("author", article.getAuthor());
            resultmap.put("title", article.getTitle());
            resultmap.put("content", article.getContent());
            resultmap.put("digest", article.getDigest());
            resultmap.put("show_cover_pic", article.getShowCoverPic());
            resultmap.put("content_source_url", article.getContentSourceUrl());
            resultmap.put("need_open_comment", article.getNeedOpenComment());
            resultmap.put("only_fans_can_comment", article.getOnlyFansCanComment());
            list.add(resultmap);
        }
        articlesmap.put("articles", list);
        String result = JsonUtil.toString(articlesmap);
        // 发起HTTP请求，获取返回结果
        map = ArticleUtil.upsertArticle(accessToken, result, "NEW");
        wxLogService.log(WxLogModule.wxLogMaterial, "上传图文素材",
            "上传永久图文素材", wxAppid, wxToken.getCorpid());
        return map;
    }

    @Override
    public Map<String, Object> updateArticles(String wxAppid, List<Article> articleList) throws Exception {
        Map<String, Object> result = new HashMap<>(8);
        WxToken wxToken = wxTokenService.getWxAccessTokenByAppId(wxAppid);
        String accessToken = wxToken.getAccess_token();
        for (Article article : articleList) {
            // 校验数据
            checkUpdateArticle(accessToken, article);
            Map<String, Object> articlesmap = new HashMap<>(16);
            articlesmap.put("media_id", article.getMediaId());
            articlesmap.put("index", article.getIndex());
            Map<String, Object> resultmap = new HashMap<>(16);
            resultmap.put("thumb_media_id", article.getThumbMediaId());
            resultmap.put("author", article.getAuthor());
            resultmap.put("title", article.getTitle());
            resultmap.put("content", article.getContent());
            resultmap.put("digest", article.getDigest());
            //设置主图
            if (article.getIndex() == 0) {
                resultmap.put("show_cover_pic", article.getIndex());
            } else {
                resultmap.put("show_cover_pic", 1);
            }
            resultmap.put("content_source_url", article.getContentSourceUrl());
            articlesmap.put("articles", resultmap);
            //转换为json 字符串
            String data = JsonUtil.toString(articlesmap);
            result = ArticleUtil.upsertArticle(accessToken, data, "UPDATE");
        }
        wxLogService.log(WxLogModule.wxLogMaterial, "修改图文素材",
            "修改永久图文素材", wxAppid, wxToken.getCorpid());
        return result;
    }

    /**
     * 图文上传数据校验
     *
     * @author lujiang
     * @date 2019/02/26 16:30
     * @param accessToken 全局唯一凭证
     * @param articleList 图文对象集合
     */
    private void checkArticle(String accessToken, List<Article> articleList) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new ServiceException("MPNEWS-001");
        }
        if (articleList.size() < 1) {
            throw new ServiceException("MPNEWS-002");
        }
        // 必输校验
        for (Article article : articleList) {
            if (StringUtils.isBlank(article.getTitle())) {
                throw new ServiceException("MPNEWS-003");
            }
            if (null == article.getThumbMediaId()) {
                throw new ServiceException("MPNEWS-004");
            }
            if (StringUtils.isBlank(article.getShowCoverPic() + "")) {
                throw new ServiceException("MPNEWS-005");
            }
            if (StringUtils.isBlank(article.getContent())) {
                throw new ServiceException("MPNEWS-006");
            }
        }
    }

    /**
     * 图文修改数据校验
     *
     * @author lujiang
     * @date 2019/02/26 16:30
     * @param accessToken 全局唯一凭证
     * @param article     图文对象
     * @throws Exception
     */
    private void checkUpdateArticle(String accessToken, Article article) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new ServiceException("MPNEWS-001");
        }
        if (null == article) {
            throw new ServiceException("MPNEWS-007");
        }
        if (StringUtils.isBlank(article.getIndex() + "")) {
            throw new ServiceException("MPNEWS-008");
        }
        if (StringUtils.isBlank(article.getMediaId())) {
            throw new ServiceException("MPNEWS-009", String.valueOf(article.getIndex()));
        }
        if (StringUtils.isBlank(article.getTitle())) {
            throw new ServiceException("MPNEWS-010", String.valueOf(article.getIndex()));
        }
        if (null == article.getThumbMediaId()) {
            throw new ServiceException("MPNEWS-011", String.valueOf(article.getIndex()));
        }
        if (StringUtils.isBlank(article.getAuthor())) {
            throw new ServiceException("MPNEWS-012", String.valueOf(article.getIndex()));
        }
        if (StringUtils.isBlank(article.getShowCoverPic() + "")) {
            throw new ServiceException("MPNEWS-013", String.valueOf(article.getIndex()));
        }
        if (StringUtils.isBlank(article.getContent())) {
            throw new ServiceException("MPNEWS-014", String.valueOf(article.getIndex()));
        }
    }

    @Override
    public Map<String, Object> uploadMaterial(String wxAppid, String type, String fileDir) throws Exception {
        Map<String, Object> result = new HashMap<>();
        WxToken wxToken = wxTokenService.getWxAccessTokenByAppId(wxAppid);
        result =  ArticleUtil.uploadMaterial(wxToken.getAccess_token(), type, fileDir);
        wxLogService.log(WxLogModule.wxLogMaterial, "上传其他类型素材",
            "上传" + type + "类型素材", wxAppid, wxToken.getCorpid());
        return result;
    }

    @Override
    public int deleteArticle(String wxAppid, String mediaId) throws Exception {
        WxToken wxToken = wxTokenService.getWxAccessTokenByAppId(wxAppid);
        int num = ArticleUtil.deleteArticle(wxToken.getAccess_token(), mediaId);
        wxLogService.log(WxLogModule.wxLogMaterial, "删除素材",
            "删除素材，mediaId => " + mediaId, wxAppid, wxToken.getCorpid());
        return num;
    }
}
